<?php
header('Access-Control-Allow-Origin:*');
header('Content-Type:application/json; charset=utf-8');
header('Access-Control-Allow-Methods:POST,GET,OPTIONS');
header('Access-Control-Allow-Headers:Content-Type,Authorization,token');
defined('BASEPATH') or exit('No direct script access allowed');
require 'JWT.php';
class ApiController extends CI_Controller {
	private $jwt;
	public $token;
	public $json;
	private $response=array(
	  'code'=>1,
	  'msg'=>'success'
	);
	public function __construct()
	{
	    parent::__construct();
		$this->jwt=new JWT();
		$headers=getallheaders();
		if (array_key_exists("Token", $headers)) {
		    $this->token=$headers["Token"];
		} else {
		    $this->token='';
		}
	}
	
	public function getKeys($keys,$method="post")
	{
		$data=array();
		$tipKeys=array();
		foreach($keys as $ck=>$cv){
			$key=$cv[0];
			$force=$cv[1];
			$msg=$cv[2];
			//print_r($cv);
			$v='';
			if($method=='post'){
				$v=$this->input->post($key);
			}else{
				$v=$this->input->get($key);
			}
			
			//如果该字段是强制字段
			if($force){
				if(isset($v)){
					if($v==''){
						array_push($tipKeys,$msg);
					}else{
						$data[$key]=$v;
					}
				}else{
					array_push($tipKeys,$msg);
				}
			}else{
				if(isset($v)){
					if($v==''){
						if(count($cv)>=4){
							$data[$key]=$cv[3];
						}else{
							$data[$key]="";
						}
					}else{
						$data[$key]=$v;
					}
				}else{
					if(count($cv)>=4){
						$data[$key]=$cv[3];
					}else{
						$data[$key]="";
					}
				}
			}

		}
		if($tipKeys){
			header('Content-Type:text/html; charset=utf-8');
			echo (json_encode(array("code"=>0,"msg"=>'请求时缺少必要参数: '.implode(",",$tipKeys)),JSON_UNESCAPED_UNICODE));
			exit();
		}
		return $data;
	}
	 
	
	
	
	//校难参数 [参数列表，请求方法]
	public function checkParams($params=[],$method="get"){
		$json = file_get_contents('php://input');
		// 将 JSON 解码为 PHP 数组
		$query_data = json_decode($json, true);	
		$tips=[];
		$rueqest_data=[];
 
		 foreach($params as $key=>$value){
			 $v=$query_data[$key];
			if($method=="get"){
				if($value[1]=="required"){
					if(is_null($v)){ //参数没有传递
						array_push($tips,$value[0]);
					}else if($v==""){
						array_push($tips,$value[0]);
					}else{
						$rueqest_data[$key]=$v;
					}
				}else{
					if(is_null($v)){ //参数没有传递
						$rueqest_data[$key]=$value[2]? $value[2]:null;
					}else if($v==""){
						$rueqest_data[$key]=$value[2]? $value[2]:null;
					}else{
						$rueqest_data[$key]=$v;
					}
				}
			}
			if($method=="post"){
				$v=$query_data[$key];				
				if($value[1]=="required"){
					if(isset($v)){
						$rueqest_data[$key]=$v;
					}else{
						array_push($tips,$value[0]);
					}
				}else{
					if(isset($v)){ 
						if($v==""){
							$rueqest_data[$key]=isset($value[2])? $value[2]:"";
						}else{
							$rueqest_data[$key]=$v;
						}
					}else{
						$rueqest_data[$key]=isset($value[2])? $value[2]:null;					
					}
				}
			}
		}
		
		
		if($tips){
			header('Content-Type:text/html; charset=utf-8');
			echo (json_encode(array("code"=>0,"msg"=>implode(",",$tips)."参数丢失"),JSON_UNESCAPED_UNICODE));
			exit();
		}
		return $rueqest_data;
	}
	/**
	 * 根据给定key去获取传递的值
	 * @param {Object} $key
	 * @param {Object} $required
	 * @param {Object} $default
	 */
	public function getPKey($key,$required,$default){
		$json = file_get_contents('php://input');
		// 将 JSON 解码为 PHP 数组
		$kvs= json_decode($json, true);
		
		//如果是必填参数
		$value=null;
		$keyexist=0;
		foreach($kvs as $k=>$v){
			if($key==$k){
				$keyexist=1;
				$value=$v;
			}
		}
				
		if(!$keyexist){
			$value=$default;
		}
    	return $value;
	}
	
	
	public function getParam($type,$key,$value){
		$json = file_get_contents('php://input');
		// 将 JSON 解码为 PHP 数组
		$query_data = json_decode($json, true);		
		
		if($type=='get'){
			$finalv="";
			$v=$query_data[$key];
			if(is_null($v)){
				$finalv=$value;
			}else if(isset($v)){
				if($v==""){
					$v=="";
				}else{
					$finalv=$v;
				}
			}else{
				$finalv=$v;
			}
			return $finalv;
		}else if($type=="post"){
			$finalv="";
			$v=$query_data[$key];
			if(is_null($v)){
				$finalv=$value;
			}else if(isset($v)){
				if($v==""){
					$v=="";
				}else{
					$finalv=$v;
				}
			}else{
				$finalv=$v;
			}
			return $finalv;
		}
	}
	
	//写入某个字段值，没有则会自动添加
	public function WRITE($key, $value)
	{
	    if (array_key_exists($key, $this->response)) {
	        $this->response[$key]=$value;
	    } else {
	        $this->response[$key]=$value;
	    }
	}
	public function RESPONSE()
	{
	    echo json_encode($this->response, JSON_UNESCAPED_UNICODE);
	}
	
	
	
	/***********************JWT相关操作*******************************/
	/* 调用JWT生成 TOKEN,并附带额外信息*/
	public function createToken($data){
		$this->jwt->setClaim($data);
		return $this->jwt->createToken();
	}
	
	
	public function verifyToken(){
		$token=$this->token;
		$decodetoken=$this->jwt->verifyToken($token);
		if(!$decodetoken){
			header('Content-Type:text/html; charset=utf-8');
			$this->WRITE("code",401);
			$this->WRITE("msg","登录状态已经失效或无权访问");
			$this->RESPONSE();
			exit();
		}
		if($decodetoken){
			return $decodetoken['claim'];
		}
		return '';
	}
	
}

